﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

///<summary>
///
///</summary>
public class BalloonAnimationComponent : MonoBehaviour
{
    [SerializeField]
    private Image Sprite;
    [SerializeField]
    public List<Sprite> animationSprites = new List<Sprite>();
    public int index;
    public string path;
    BalloonType balloonType;
    Vector3 rotation = new Vector3(0, 0, 0);
    Color32[] color32s = new Color32[] { new Color32(44, 179, 168, 255), new Color32(236, 82, 156, 255),
        new Color32(253, 181, 77, 255), new Color32(100, 219, 234, 255),new Color32(207,129,252,255),new Color32(254,218,50,255),new Color32(252,48,68,255),
    new Color32(208,125,255,255),new Color32(208,125,255,255),new Color32(208,125,255,255),new Color32(173,156,115,255)};
    private void OnEnable()
    {
        if (Sprite == null) Sprite = GetComponent<Image>();
        balloonType = GetComponent<BalloonInputKeyComponent>().GetBalloonType();
        Sprite.color = new Color(255,255,255,255);
    }
    private int AnimationAmount { get { return animationSprites.Count; } }
    public void PlayAnimation(float time)
    { 
        if (AnimationAmount < 1)
        {
            for (int i = 1; i < index; i++)
            {
                string spritePath = path + i;
                animationSprites.Add(Resources.Load<Sprite>(spritePath));
            }
        }
        StartCoroutine(PlayAnimationOnce(time));
    }

    //循环播放
    private IEnumerator PlayAnimationForwardIEnum()
    {
        int index = 0;//可以用来控制起始播放的动画帧索引
        gameObject.SetActive(true);
        while (true)
        {
            //当我们需要在整个动画播放完之后 重复播放后面的部分 就可以展现我们纯代码播放的自由性
            if (index < AnimationAmount - 1)
            {
                Sprite.sprite = animationSprites[index];
                index++;
            }
            else
            {
                index = 0;
            }
            yield return new WaitForSeconds(0.03f);//等待间隔 控制动画播放速度
        }
    }

    //播放一次
    private IEnumerator PlayAnimationOnce(float time)
    {
        int index = 0;//可以用来控制起始播放的动画帧索引
        gameObject.SetActive(true);
        while (true)
        {
            //当我们需要在整个动画播放完之后 重复播放后面的部分 就可以展现我们纯代码播放的自由性
            if (index < AnimationAmount - 1)
            {
                Sprite.sprite = animationSprites[index];
                Sprite.color = color32s[(int)balloonType];
                index++;
            }          
            else if (index == AnimationAmount - 1)
            {
                Sprite.color = new Color32(0, 0, 0, 0);
				gameObject.SetActive(false);
				gameObject.transform.SetParent(BalloonFactory.Instance.transform);
                gameObject.transform.eulerAngles = rotation;
            }
            yield return new WaitForSeconds(time);//等待间隔 控制动画播放速度
        }
    }

}
